#include "ScnsMem.c.h"

#if defined(SCNS_MEM_ENABLE)&&SCNS_MEM_ENABLE==1

#include "ScnsBspMem.c.h"
#include "ScnsColor.h"
#include "ScnsLed.h"
#include "ScnsMath.h"
#include "ScnsIwdg.h"

uint32 __memset_acc_cnt=0,__memset_call_cnt=0,__memcpy_acc_cnt=0,__memcpy_call_cnt=0;

#if defined(__HAL_RCC_DMA2D_IS_CLK_ENABLED)

extern ScnsStatus dma2dLock(void);
extern ScnsStatus dma2dStart(void);

ScnsStatus scnsBspMemcpy(void*dst,const void*src,size_t n)
{
    __memcpy_call_cnt+=1;
    SCNS_ASSERT_ON_RUN(n%SCNS_MEMCPY_BSP_MIN_SIZE==0);
    if(!(((uintptr_t)(dst)+n<=(uintptr_t)(src))||((uintptr_t)(src)+n)<=(uintptr_t)(dst))){return SCNS_STATUS_NOT_SUPPORT;}
    scnsCheckStatus(dma2dLock());
    scnsMemCleanDCache((const uint8*)src,n);
    const size_t sizeB=n/4/2048;
    SCNS_ASSERT_ON_RUN(sizeB<=65535);
    DMA2D->CR=0x00000000UL;
    DMA2D->FGOR=0;
    DMA2D->OOR=0;
    DMA2D->FGPFCCR=LTDC_PIXEL_FORMAT(SCNS_COLOR_FORMAT_ARGB8888);
    DMA2D->OPFCCR=LTDC_PIXEL_FORMAT(SCNS_COLOR_FORMAT_ARGB8888);
    DMA2D->FGMAR=(uintptr_t)(src);
    DMA2D->OMAR=(uintptr_t)(dst);
    DMA2D->NLR=((uintptr_t)(2048<<16))|(sizeB);
    scnsCheckStatus(dma2dStart());
    scnsMemInvalidateDCache((uint8*)dst,n);
    ++__memcpy_acc_cnt;
    return SCNS_STATUS_OK;
}

ScnsStatus scnsBspMemset(void*dst,int c,size_t n)
{
    __memset_call_cnt+=1;
    SCNS_ASSERT_ON_RUN(n%SCNS_MEMCPY_BSP_MIN_SIZE==0);
    scnsCheckStatus(dma2dLock());
    const size_t sizeB=n/4/2048;
    SCNS_ASSERT_ON_RUN(sizeB<=65535);
    DMA2D->CR=0x00030000UL;
    DMA2D->OCOLR=(((uint8)c)<<24)|(((uint8)c)<<16)|(((uint8)c)<<8)|(((uint8)c));
    DMA2D->OPFCCR=LTDC_PIXEL_FORMAT(SCNS_COLOR_FORMAT_ARGB8888);
    DMA2D->OOR=0;
    DMA2D->OMAR=(uintptr_t)(dst);
    DMA2D->NLR=((uintptr_t)(2048<<16))|(sizeB);
    scnsCheckStatus(dma2dStart());
    scnsMemInvalidateDCache((uint8*)dst,n);
    ++__memset_acc_cnt;
    return SCNS_STATUS_OK;
}

#endif

#endif
